<template>
  <div id="qcMonthQueryDiv">
    <Breadcrumb content="月质控信息" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="15">
          <div class="saveBtn">
            <vxe-checkbox v-model="searchForm.isShowAll" size="small" content="显示过期的质控品" checked-value="1" unchecked-value="0" @change="findMaterialItemTree"></vxe-checkbox>
          </div>
          <vxe-toolbar perfect>
            <template #buttons>
              <!-- <div class="smallToolTitle">仪器</div>
              <vxe-select v-model="searchForm.instrIds" multiple :filterable="true" clearable @change="valueChangeEvent">
                <vxe-option v-for="instr in instrList" :key="instr.id" :value="instr.id" :label="instr.instrName"></vxe-option>
              </vxe-select> -->
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="treeloading" @click="findMaterialItemTree"></vxe-button>
            </template>
          </vxe-toolbar>
          <el-scrollbar style="height: calc(100% - 40px)">
            <div class="sampleType">
              <el-scrollbar>
                <el-tree :expand-on-click-node="false" :default-expanded-keys="expandedkeys" :data="materialItemTree" :props="defaultProps" node-key="id" ref="materialItemTreeRef" highlight-current class="tools-tree" @node-click="handleClickType" v-loading="treeloading">
                  <template #default="{ data, node }">
                    <div style="float: right">
                      <img :src="`${getAssetsFile('images/qc/' + data.type + '.png')}`" style="width: 15px; height: 15px; margin-right: 10px" />
                      {{ data.name }}
                    </div>
                  </template>
                </el-tree>
              </el-scrollbar>
            </div>
          </el-scrollbar>
        </Pane>
        <Pane size="55">
          <el-tabs type="border-card" v-model="activeTab" @tab-click="tabClick">
            <el-tab-pane label="Z-分数图" name="Z"> </el-tab-pane>
            <el-tab-pane label="Levey-Jennings图" name="LJ"></el-tab-pane>
            <div class="tab-content" v-if="activeTab === 'LJ' || activeTab === 'Z'">
              <Splitpanes horizontal>
                <Pane size="66">
                  <el-scrollbar height="100%">
                    <QcEChart id="qcEchart" ref="qcEchartRef"></QcEChart>
                  </el-scrollbar>
                </Pane>
                <Pane size="34">
                  <QcResultTable id="qcResultTable" ref="qcResultTableRef"></QcResultTable>
                </Pane>
              </Splitpanes>
            </div>
          </el-tabs>
        </Pane>
        <Pane size="30">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">指定日期</div>
              <vxe-input v-model="resultSearchForm.qcDate" placeholder="选择月份" type="month" valueFormat="yyyy-MM-dd" :disabled="disabledTag" @change="findMaterialResultList"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :disabled="disabledTag" :loading="rloading" @click="findMaterialResultList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="disabledTag" @click="addMaterialResult"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="disabledTag" @click="deleteMaterialResult"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="disabledTag" @click="saveMaterialResult"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBox">
            <vxe-table ref="materialResultTableRef" :data="materialResultList" :loading="rloading" @current-change="materialResultRowClick" class="mytable-scrollbar" border="inner" align="center" height="auto" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
              <vxe-column field="qcDate" title="质控日期" width="80" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.qcDate" placeholder="" type="text"></vxe-input>
                </template>
              </vxe-column>

              <vxe-column field="result" title="结果数据" width="80" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.result" placeholder="" type="text"></vxe-input>
                </template>
              </vxe-column>
              <!-- <vxe-column field="qcSequence" title="次数" width="50" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.qcSequence" placeholder="" type="text"></vxe-input>
                </template>
              </vxe-column> -->
              <vxe-column field="mean" title="靶值" width="80">
              </vxe-column>
              <vxe-column field="sd" title="SD值" width="80">
              </vxe-column>
              <vxe-column field="z" title="z值" width="80">
              </vxe-column>
              <vxe-column field="isAlarm" title="失控" width="80">
                <template #default="{ row }">
                  <span>{{ formatIsAlarmDesc(row) }}</span>
                </template>
              </vxe-column>
              <vxe-column field="outControlRules" title="失控规则">
              </vxe-column>

            </vxe-table>
          </div>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { DateToString, formatDateTime, getAssetsFile } from '@/utils/common';
import { AppStore } from '@/stores/store';
import { isEmpty } from 'lodash';
import QcEChart from './QcEChart.vue'; // e-charts 图
import QcResultTable from './QcResultTable.vue';
// 全局变量定义区 ==========
let store = AppStore();
let { proxy }: any = getCurrentInstance();
// 最左侧的树
let defaultProps = {
  children: 'children',
  label: 'name'
};
let instrList: any = reactive([]); //左侧仪器下拉项
let materialResultList: any = reactive([]);
let treeloading = ref(false); //质控靶值树上的刷新
let materialItemTree: any = reactive([]); //最左侧质控靶值设定树数据
let expandedkeys: any = reactive([]);
let sltMaterItem: any = reactive({}); //最左侧树选中行
let disabledTag = ref(true);
let rloading = ref(false);
const activeTab = ref('Z');
let chartHeight: number = ref();

let searchForm = ref({
  searchValue: '',
  instrId: '',
  instrIds: [],
  isShowAll: '0'
});
let resultSearchForm = ref({
  searchValue: '',
  qcDate: DateToString(new Date())
});
// 页面加载时更新
onMounted(() => {
  chartHeight = document.documentElement.clientHeight - 60 - 40 - 49 - 10 - 10;
  findInstrSetupList();
  findMaterialItemTree(); // 获取最左侧质控靶值树数据
});
// 获取左侧仪器下拉选项数据(标题)
function findInstrSetupList() {
  instrList.length = 0; //放入数据前清空数据
  const url = '/lis/instrSetup/getInstrSetupList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '' }
    })
    .then((res: any) => {
      instrList.push(...res.data);
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

// 仪器下拉选择 改变
function valueChangeEvent() {
  findMaterialItemTree();
}

// 获取最左侧质控靶值树 刷新
function findMaterialItemTree() {
  treeloading.value = true;
  materialItemTree.length = 0; //放入数据前清空数据
  expandedkeys.length = 0;
  sltMaterItem = reactive({});
  const url = '/api/qc/qcMaterialItem/findMaterialItemTree';
  proxy.$http
    //注意此处的数据条数
    .get(url, { params: { isShowAll: searchForm.value.isShowAll, instrIds: searchForm.value.instrIds } })
    .then((res: any) => {
      if (!IsEmpty(res.data)) {
        materialItemTree.push(...res.data);
        //默认选中第一条
        //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
        // const sltObj = getChildren(materialItemTree[0]);
        // // 光标定位在字典分类列表的第一项
        // setCurTypeNode(sltObj.id);
        // if (sltObj.isSearch == '0') {
        //   sltMaterItem = sltObj;
        // }
        // findMaterialResultList();

        getExpandedkeys();
        if (!sltMaterItem.id) {
          disabledTag.value = true;
        } else {
          //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
          disabledTag.value = false;
        }
      }
      treeloading.value = false;
    })
    .catch((err: any) => {
      treeloading.value = false;
      VxeMessage('获取最左侧质控靶值树异常', VxeNotifyType.error);
    });
}

//点击左侧树
function handleClickType(obj: any, node: any, data: any) {
  const isSearch = obj.isSearch;
  sltMaterItem = reactive({});
  if (isSearch == '0') {
    sltMaterItem = obj;
  }

  //如果点击的当前行数据是父级，那就禁用质控品维护的按钮
  if (!sltMaterItem.id) {
    disabledTag.value = true;
    materialResultList.length = 0; //放入数据前清空数据
  } else {
    //如果点击的当前行数据是子集，那就不需要禁用质控品维护的按钮
    disabledTag.value = false;
    findMaterialResultList();
  }
}
let sltMaterialResult: any = {};

// 获取质控靶值设定表格数据 刷新
function findMaterialResultList() {
  handleSearch();
  const QCDate = new Date(formatDateTime(resultSearchForm.value.qcDate, 'yyyy-MM-01')).valueOf();
  rloading.value = true;
  materialResultList.length = 0; //放入数据前清空数据
  countDaysByMonth();
  const url = '/api/qc/qcMaterialItemResult/getQcResultByMonth';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        pid: sltMaterItem.id,
        qcMonth: formatDateTime(new Date(resultSearchForm.value.qcDate), 'yyyy-MM')
      }
    })
    .then((res: any) => {
      materialResultList.length = 0;
      //materialResultList.push(...res.data);
      for (let i = 1; i <= qcDays; i++) {
        let resDayResult = res.data.find((item) => item.day === i);
        if (!IsEmpty(resDayResult)) {
          materialResultList.push(...resDayResult.sequenceResults);
        } else {
          materialResultList.push({
            id: '',
            materialId: sltMaterItem.materialId,
            materialItemId: sltMaterItem.id,
            qcItemId: sltMaterItem.qcItemId,
            instrId: sltMaterItem.instrId,
            itemDictId: sltMaterItem.itemDictId,
            batchNum: sltMaterItem.batchNum,
            horizontal: sltMaterItem.horizontal,
            qcDate: formatDateTime(new Date(QCDate + 24 * 60 * 60 * 1000 * (i - 1)), 'yyyy-MM-dd'),
            qcNo: sltMaterItem.qcNo,
            qcSequence: 1
          });
        }
      }

      if (materialResultList.length > 0) {
        materialResultRowClick({ row: materialResultList[0] });
      } else {
        sltMaterialResult = {};
      }
      rloading.value = false;
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取右侧质控项目表格数据异常', VxeNotifyType.error);
    });
}
// 左侧表格 点击当前行
function materialResultRowClick({ row }) {
  if (isEmpty(row)) {
    sltMaterialResult = {};
  } else {
    (proxy.$refs.materialResultTableRef as any).setCurrentRow(row);
    sltMaterialResult = row;
  }
}

function addMaterialResult() {
  if (isEmpty(sltMaterItem)) {
    VxeMessage('请选择项目', VxeNotifyType.error);
  } else {
    let obj = findMaxCodeByDate(sltMaterialResult, materialResultList);
    const record: any = {
      id: '',
      materialId: sltMaterItem.materialId,
      materialItemId: sltMaterItem.id,
      qcItemId: sltMaterItem.qcItemId,
      instrId: sltMaterItem.instrId,
      itemDictId: sltMaterItem.itemDictId,
      batchNum: sltMaterItem.batchNum,
      horizontal: sltMaterItem.horizontal,
      qcDate: sltMaterialResult.qcDate,
      qcNo: sltMaterItem.qcNo,
      qcSequence: obj.qcSequence + 1
    };
    const index = materialResultList.findIndex((item) => item === sltMaterialResult);
    materialResultList.splice(index + 1, 0, record);
    //materialResultList.push(record);
  }
}

// 左侧保存
async function saveMaterialResult() {
  if (isEmpty(sltMaterItem)) {
    VxeMessage('请选择项目', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.materialResultTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = materialResultList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateRules = [] as any[];
      updateRecords.forEach((e: any) => {
        const iIRule: any = {
          id: e.id,
          materialId: e.materialId,
          materialItemId: e.materialItemId,
          qcItemId: e.qcItemId,
          instrId: e.instrId,
          itemDictId: e.itemDictId,
          batchNum: e.batchNum,
          horizontal: e.horizontal,
          qcDate: e.qcDate,
          qcNo: e.qcNo,
          result: e.result,
          qcSequence: e.qcSequence
        };

        sveOrupdateRules.push(iIRule);
      });
      InsertRecords.forEach((e: any) => {
        const iIRule: any = {
          id: e.id,
          materialId: e.materialId,
          materialItemId: e.materialItemId,
          qcItemId: e.qcItemId,
          instrId: e.instrId,
          itemDictId: e.itemDictId,
          batchNum: e.batchNum,
          horizontal: e.horizontal,
          qcDate: e.qcDate,
          qcNo: e.qcNo,
          result: e.result,
          qcSequence: e.qcSequence
        };
        sveOrupdateRules.push(iIRule);
      });
      if (sveOrupdateRules.length > 0) {
        const url = '/api/qc/qcMaterialItemResult/saveOrUpdateMaterialResult';
        const obj: any = {
          materialId: sltMaterItem.materialId,
          materialItemId: sltMaterItem.id,
          qcItemId: sltMaterItem.qcItemId,
          instrId: sltMaterItem.instrId,
          itemDictId: sltMaterItem.itemDictId,
          method: sltMaterItem.method,
          batchNum: sltMaterItem.batchNum,
          qcNo: sltMaterItem.qcNo,
          horizontal: sltMaterItem.horizontal,
          itemDefine: sltMaterItem.itemDefine,
          qcMonth: formatDateTime(new Date(resultSearchForm.value.qcDate), 'yyyy-MM')
        };
        obj.iqcResults = sveOrupdateRules;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            rloading.value = false;
            findMaterialResultList();
            // this.findIQCMaterialResultList('', false);
            VxeMessage('保存成功', VxeNotifyType.success); //保存成功显示成功类型
          })
          .catch((res: any) => {
            rloading.value = false;
            VxeMessage('保存失败', VxeNotifyType.error);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}

function findMaxCodeByDate(date, items) {
  // 过滤出指定日期的所有对象
  const filteredItems = items.filter((item) => item.qcDate === date.qcDate);

  // 如果该日期没有对象，返回null或空对象
  if (filteredItems.length === 0) {
    return null; // 或者 {} 根据你的需求
  }

  // 找到最大code值的对象
  const maxCodeItem = filteredItems.reduce((max, item) => {
    if (item.qcSequence > max.qcSequence) {
      return item;
    }
    return max;
  }, filteredItems[0]); // 使用第一个元素作为初始比较值

  return maxCodeItem;
}
const qcEchartRef: any = ref(null);
const qcResultTableRef: any = ref(null);

// 查询 参数val用来区分Z分数图和LJ图
function handleSearch() {
  const inputDate = formatDateTime(new Date(resultSearchForm.value.qcDate), 'yyyy-MM'); // 输入示例
  const dateObj = moment(inputDate, 'YYYYMM'); // 解析输入年月‌:ml-citation{ref="4" data="citationList"}
  // 当月第一天
  const firstDay = dateObj.startOf('month').format('YYYY-MM-DD'); // 格式化为yyyymmdd‌:ml-citation{ref="4,8" data="citationList"}
  // 当月最后一天
  const lastDay = dateObj.endOf('month').format('YYYY-MM-DD'); // 格式化为yyyymmdd‌:ml-citation{ref="4,8" data="citationList"}
  let iqcResultForm = {
    itemDictId: sltMaterItem.itemDictId,
    iqcMaterialIds: [sltMaterItem.materialId],
    QCDateS: firstDay + ' 00:00:00',
    QCDateE: lastDay + ' 23:59:59'
  };
  proxy.$nextTick(() => {
    if (activeTab.value === 'Z' || activeTab.value === 'LJ') {
      qcEchartRef.value?.getEchartData(activeTab, iqcResultForm, chartHeight);
      qcResultTableRef.value?.getIQCResultList(activeTab, iqcResultForm);
      qcResultTableRef.value?.getIQCMaterialsInfoAsync(activeTab, iqcResultForm);
    }
  });
}

function tabClick() {
  proxy.$nextTick(() => {
    if (activeTab.value === 'Z' || activeTab.value === 'LJ') {
      handleSearch();
    }
  });
}

function deleteMaterialResult() {
  if (isEmpty(sltMaterialResult)) {
    VxeMessage('请选择删除的结果', VxeNotifyType.error);
  } else {
    proxy
      .$confirm('确定要删除当前选中的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        if (!isEmpty(sltMaterialResult.id)) {
          const data = { iqcResults: [sltMaterialResult] };
          const url = '/api/qc/qcMaterialItemResult/batchDeleteMaterialItemResult';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findMaterialResultList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        } else {
          //页面删除未保存的数据  不走接口
          const iindex = materialResultList.findIndex((item) => item == sltMaterialResult);
          materialResultList.splice(iindex, 1);
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

// 光标定位在指定字典分类上
function setCurTypeNode(nodeId) {
  proxy.$nextTick(() => {
    const treeName = 'materialItemTreeRef';
    const tree: any = proxy.$refs[treeName];
    tree.setCurrentKey(nodeId);
  });
}
// ------------------------------------------------------------
//**判断为空*/
function IsEmpty(value: any) {
  if (value === undefined || value === '' || value === null) {
    return true;
  }
  if (JSON.stringify(value) === '{}') {
    return true;
  }
  return false;
}

function getExpandedkeys() {
  for (const materialItem of materialItemTree) {
    pusExpandedkeys(materialItem);
  }
}

function pusExpandedkeys(obj: any) {
  const children = obj.children;
  if (obj.type == 'instrClass') {
    //expandedkeys.push(obj.id);
  }
  if (!IsEmpty(children) && children.length > 0) {
    for (const ch of children) {
      pusExpandedkeys(ch);
    }
  }
}
let qcDays = 0; //每月质控天数

// 根据日期计算天数
function countDaysByMonth() {
  const year = new Date(resultSearchForm.value.qcDate).getFullYear();
  const month = new Date(resultSearchForm.value.qcDate).getMonth() + 1;
  qcDays = new Date(year, month, 0).getDate();
}

function formatIsAlarmDesc(row) {
  if (!IsEmpty(row.isOutControl)) {
    return row.isOutControl ? '失控' : '在控';
  } else {
    return '';
  }
}
</script>

<style lang="scss" scoped>
#qcMonthQueryDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 显示过期的质控品按钮
      .saveBtn {
        float: right;
        //margin: 0px 0px 0px 0px;
        margin-top: 10px;
        margin-right: 10px;
      }

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      // 最右侧质控靶值设定表格
      .tableBox {
        height: calc(100% - 40px);
      }
    }

    :deep(.result-table) {
      .number-right .vxe-cell {
        text-align: right;
        span {
          display: inline-block;
          width: calc(100% - 12px);
        }
      }
      .el-icon-warning {
        color: red;
      }
      .el-icon-warning-outline {
        color: $warning-color;
      }
      .el-icon-success {
        color: $success-color;
      }
      .zS2 {
        color: $warning-color;
      }
      .zS3 {
        color: $danger-color;
      }
      .zS-2 {
        color: $brand-color;
      }
      .zS-3 {
        color: #6600ff;
      }
    }
  }

  :deep(.drawerBulkModal) {
    inset: 50px 0 0 70px !important;
  }
  :deep(.el-drawer__body) {
    .iqcOutControl {
      width: 800px;
      // margin: 0 auto;
      transform: translateX(65%);
    }
  }
}
</style>